<?php

declare(strict_types=1);

namespace app\api\controller;

use think\facade\View;
use think\response\Json;
use app\common\model\Draw as DrawModel;
use app\common\model\Product;
use think\exception\ValidateException;
use app\common\tool\Result;
use app\common\controller\Config;

class Draw extends Base
{
    /**
     * 兑换详情
     */
    public function detail()
    {
        try {
            $info = Product::where(['cate_1' => 2, 'status' => 1])->field('id,title,images,price,vip_price,content')->find();
            if (empty($info)) {
                return Result::fail('兑换商品不存在！');
            }
            $info->images = explode(',', $info->images);
            $url = 'http://' . $_SERVER['SERVER_NAME'] . '/uploads/';
            $info->content = htmlspecialchars_decode(str_replace('/uploads/', $url, $info->content));
            $info->content = str_replace('\\', '', $info->content);
            return Result::success('获取成功！', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 兑换记录
     */
    public function getList(): Json
    {
        $param = $this->request->param();
        try {
            $map = ['uid' => $this->user->id];
            return Result::fastReturn(DrawModel::getPageList($map, 'id,account,mode,money,create_time,status', $param['page'], 20, false));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 添加兑换
     */
    public function save(): Json
    {
        $param = $this->request->post();
        try {
            $param['account'] = 'bonus_3';
            $this->validate($param, 'Draw');
            return Result::fastReturn(DrawModel::add($param, $this->user, Config::lists()));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
    }
}
